import config from '../../utils/config.js'
import { Target, Config, HttpUtil } from '../../utils/http_util.js'

/**
 * 单个图片
 * @param imageData 数据json对象
 * @param status 上传状态 ready:准备上传，uploading：上传中，success: 上传成功，fail：上传失败
 * @param isPlusBtn 是否为选择按钮
 */
function ImageItem(imageData, status = '', isPlusBtn = false, process, aptitudeType) {
  /** id随机生成 */
  this.id = Math.random().toString(36).substr(2)
  this.imageData = imageData

  /** success，fail, uploading, ready */
  this.status = status
  this.isPlusBtn = isPlusBtn
  this.process = process
  this.aptitudeType = aptitudeType

  this.autoUpload = true

  this.checkUpload = function (callback) {
    if(this.status == 'ready') {
      this.upload(callback)
    }
  }

  this.upload = function (callback) {
    let self = this
    self.isPlusBtn = false
    self.status = 'uploading'
    const uploadTask = wx.uploadFile({
      url: Config.ctx + Target.self + 'upload/picture',
      filePath: this.imageData,
      name: 'file',
      formData: {
        id: this.data.usertype,
        userType:this.data.userInfo.id
      },
      success: function (res) {
        if (res.statusCode != 200) {
          self.status = 'fail'
          callback && callback(self)
          console.error('image upload fail: ', res.errMsg)
          return
        }
        let resp = JSON.parse(res.data)

        self.imageData = resp.uploadFileInfo[Object.keys(resp.uploadFileInfo)[0]][0]
        self.status = 'success'
        callback && callback(self)
      },
      fail: function (res) {
        self.status = 'fail'
        callback && callback(self)
        console.error('image upload fail: ', res)
      }
    })

    uploadTask.onProgressUpdate((res) => {
      self.taskInfo = res
      callback && callback(self, res)
    })
  }
}

module.exports = {
  ImageItem
}